<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Price_Car extends ORM
{
    /**
     * @param $params
     * @return array
     * 插入报价信息
     */
    public static function set_calendar_quote($params)
    {
        $params = json_decode($params,true);
        $start_time = strtotime($params['start_time']);
        $end_time = strtotime($params['end_time']);

        $total_number = DB::select(DB::expr('min(number) AS number'))->from('car_suit_number')
            ->where("suit_id={$params['suit_id']} and number!='-1' and day>={$start_time} and day<={$end_time}")
            ->execute()->get('number');
        if($params['number']>$total_number && $total_number>0){
            $date = DB::select()->from('car_suit_number')
                ->where("suit_id={$params['suit_id']} and number={$total_number} and day>={$start_time} and day<={$end_time}")
                ->execute()->get('day');
            return array(
                'status' => false,
                'msg'    => date('Y-m-d',$date).'当前时间，库存不支持所设限购数',
            );
        }

        $day_num = ($end_time-$start_time)/86400;
        $product_id = DB::select()->from('car_suit')->where("id={$params['suit_id']}")->execute()->get('carid');
        $number = $params['number']?$params['number']:0;
        $adultprice = bcadd($params['adultbasicprice'],$params['adultprofit'],2);

        $insert_arr = array();
        $update_arr = array(
            'adultbasicprice' => "adultbasicprice = CASE ",
            'adultprofit'     => "adultprofit = CASE ",
            'adultprice'      => "adultprice = CASE ",
            'number'          => "number = CASE ",
        );
        $update_id = array();
        $update_day = array();
        for($i=0;$i<=$day_num;$i++){
            $start_time = $i>0?$start_time+86400:$start_time;
            $num = DB::select()->from('car_suit_number')
                ->where('suit_id', '=', $params['suit_id'])
                ->and_where('day', '=', $start_time)
                ->execute()
                ->get('number');
            if(!$num){
                continue;
            }
            if($num<$params['number'] && $num!='-1'){
                continue;
            }
            $is_exist = DB::select()->from('car_suit_price')
                ->where("suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']}")
                ->execute()->current();
            if($is_exist){
                $state = false;
                switch ($params['price_rule'])
                {
                    case 1:
                        $state = true;
                        break;
                    case 2:
                        $week = date('w',$start_time)>0?date('w',$start_time):7;
                        if(in_array($week,$params['week_val'])){
                            $state = true;
                        }
                        break;
                    case 3:
                        $month = date('j',$start_time);
                        if(in_array($month,$params['month_val'])){
                            $state = true;
                        }
                        break;
                }
                if($state){
                    array_push($update_id,$is_exist['suitid']);
                    array_push($update_day,$is_exist['day']);
                    $update_arr['adultbasicprice'] .= "WHEN suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']} THEN '{$params['adultbasicprice']}' ";
                    $update_arr['adultprofit']     .= "WHEN suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']} THEN '{$params['adultprofit']}' ";
                    $update_arr['adultprice']      .= "WHEN suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']} THEN '{$adultprice}' ";
                    $update_arr['number']          .= "WHEN suitid={$params['suit_id']} and day={$start_time} and supplier_channel_id={$params['channel_id']} THEN '{$number}' ";
                }
            }else{
                $state = false;
                switch ($params['price_rule'])
                {
                    case 1:
                        $state = true;
                        break;
                    case 2:
                        $week = date('w',$start_time)>0?date('w',$start_time):7;
                        if(in_array($week,$params['week_val'])){
                            $state = true;
                        }
                        break;
                    case 3:
                        $month = date('j',$start_time);
                        if(in_array($month,$params['month_val'])){
                            $state = true;
                        }
                        break;
                }
                if($state){
                    $insert_sql = "({$product_id},{$params['suit_id']},{$start_time},'{$params['adultbasicprice']}','{$params['adultprofit']}','{$adultprice}',{$number},{$params['channel_id']})";
                    array_push($insert_arr,$insert_sql);
                }else{
                    continue;
                }
            }
        }

        if(count($insert_arr)>0){
            $insert_sql = "INSERT INTO sline_car_suit_price(`carid`,`suitid`,`day`,`adultbasicprice`,`adultprofit`,`adultprice`,`number`,`supplier_channel_id`) VALUES ";
            $insert_sql.= implode(',',$insert_arr);
            $result = DB::query(1, $insert_sql)->execute();
        }
        if(count($update_id)>0){
            $update_sql = "UPDATE sline_car_suit_price SET ";
            $update_id = implode(',',$update_id);
            $update_day = implode(',',$update_day);
            foreach ($update_arr as $k=>$v){
                $update_sql.= $v."ELSE {$k} END,";
            }
            $update_sql = substr($update_sql,0,strlen($update_sql)-1);
            $update_sql.= " WHERE suitid IN({$update_id}) and day IN({$update_day}) ";
            $result = DB::query(1, $update_sql)->execute();
        }

        return array(
            'status' => $result || $result===0?true:false,
            'msg'    => $result || $result===0?'设置成功':'设置失败',
        );
    }

    public static function set_single_price($params)
    {
        $params = json_decode($params,true);
        $day = strtotime($params['set_date']);

        $total_number = DB::select()->from('car_suit_number')->where("suit_id={$params['suit_id']} and day={$day}")->execute()->get('number');
        if(empty($total_number)){
            return array(
                'status' => false,
                'msg'    => '当前日期没有总库存！',
            );
        }
        if($params['number']>$total_number && $total_number!='-1'){
            return array(
                'status' => false,
                'msg'    => '限购数不得大于总库存',
            );
        }

        $data = array(
            'adultbasicprice' => $params['adultbasicprice'],
            'adultprofit'     => $params['adultprofit'],
            'adultprice'      => bcadd($params['adultbasicprice'],$params['adultprofit'],2),
            'number'          => $params['number_type']==1?-1:$params['number'],
        );

        $exists = DB::select()
            ->from('car_suit_price')
            ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id={$params['channel_id']}")
            ->execute()
            ->current();
        if($exists){
            $result = DB::update('car_suit_price')->set($data)
                ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id={$params['channel_id']}")
                ->execute();
        }else{
            $_suit=DB::select()
                ->from('car_suit')->where("id={$params['suit_id']} ")
                ->execute()
                ->current();
            $data['suitid']=$params['suit_id'];
            $data['carid']=$_suit['carid'];
            $data['supplier_channel_id']=$params['channel_id'];
            $data['day']=$day;
            $result = DB::insert('car_suit_price', array_keys($data))->values(array_values($data))->execute();
        }



        return array(
            'status'          => $result || $result===0?true:false,
            'msg'             => $result || $result===0?'设置成功':'设置失败',
            'price'           => $data['adultprice'],
            'number'          => $params['number'],
            'date'            => $params['set_date'],
        );
    }

    /**
     * @param $params
     * @return array
     * 根据渠道id获取报价信息
     */
    public static function get_suit_price($params)
    {
        $params = json_decode($params,true);
        $year = empty($params['year'])?date('Y'):$params['year'];
        $month = empty($params['month'])?date('m'):$params['month'];
        $start_time = strtotime($year.'-'.$month.'-01');
        $last_day = date('t',$start_time);
        $end_time = strtotime($year.'-'.$month.'-'.$last_day);

        $allowed_days = array();
        $list = DB::select()->from('car_suit_price')
            ->where("
                suitid='{$params['suit_id']}' 
                and day>={$start_time} 
                and day<={$end_time} 
                and supplier_channel_id={$params['channel_id']}
            ")
            ->execute()->as_array();
        foreach ($list as &$row)
        {
            $row['date'] = date('Y-m-d',$row['day']);
            $allowed_days[] = $row['date'];
            $row['price'] = empty($row['price'])?'暂未报价':$row['price'];
            $row['number'] = $row['number']==-1?'不限':$row['number'];
            $row['team_number'] = $row['team_number']==0?'不限':$row['team_number'];
        }

        return array(
            'list'         => $list,
            'starttime'    => date('Y-m-d',$start_time),
            'allowed_days' => $allowed_days
        );
    }

    /**
     * @param $params
     * @return bool[]
     * 清除报价
     */
    public static function delete_price($params)
    {
        $params = json_decode($params,true);
        DB::delete('car_suit_price')
            ->where("suitid={$params['suit_id']} and supplier_channel_id IN({$params['channel_id']})")
            ->execute();

        return array(
            'status' => true,
        );
    }

    /**
     * @param $params
     * @return array
     * 渠道产品列表
     */
    public static function channel_product_list($params)
    {
        $params = json_decode($params,true);
        $date = strtotime(date('Ymd'));
        $page = ($params['page']-1)*$params['page_size'];

        $sql = "SELECT a.id,a.title,a.status,a.ishidden FROM sline_car AS a ";
        $sql.= "LEFT JOIN sline_car_suit_price AS b ON(a.id=b.carid) ";
        $sql.= "WHERE a.supplierlist={$params['supplier_id']} AND b.day>={$date} ";
        if($params['keyword']){
            $sql.= "AND (a.title LIKE '%{$params['keyword']}%' OR a.id='{$params['keyword']}') ";
        }
        $sql.= "GROUP BY a.id ";
        $sql.= "ORDER BY a.modtime DESC,a.addtime DESC ";
        $total = DB::query(1, $sql)->execute()->count();
        $sql.= "LIMIT {$page},{$params['page_size']} ";
        $list = DB::query(1, $sql)->execute()->as_array();
        if(!$list){
            return array('status'=>false,'msg'=>'没有匹配的租车产品！');
        }
        foreach ($list as &$v){
            $v['status_name'] = Model_Supplier::status_name($v['status']);
            $max_day = DB::select(DB::expr('max(day) AS day') )->from('car_suit_price')->where("day>{$date} and carid={$v['id']}")->execute()->get('day');
            $v['time_validity'] = date('Y-m-d',$max_day);
        }

        return array(
            'status'     => true,
            'list'       => $list,
            'total_page' => ceil($total/$params['page_size'])
        );
    }

    public static function rm_oneday_price($params){
        $params = json_decode($params,true);
        $day = strtotime($params['set_date']);
        DB::delete('car_suit_price')
            ->where("suitid={$params['suit_id']} and day={$day} and supplier_channel_id IN({$params['channel_id']})")
            ->execute();
        return array(
            'date'=>$params['set_date'],
            'status' => true,
            'msg' =>  '单日删除成功',
        );
    }
}